package com.bolt.common.db;

import com.bolt.convention.data.code.CommonCode;
import com.bolt.convention.exception.ServiceException;
import com.bolt.common.reflect.ClassUtil;

import java.sql.*;
import java.util.Properties;

/**
 * Created by Administrator on 2018/2/2.
 */
public class DbHelper {

    public static void close(ResultSet rs, PreparedStatement ps, Statement... statements) {
        try {
            if (ps != null) {
                ps.close();
            }
            if (rs != null) {
                rs.close();
            }
            for (Statement s : statements) {
                s.close();
            }
        } catch (Exception e) {
        }
    }

    public static void close(ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
        }
    }

    public static void close(Statement st) {
        try {
            if (st != null) {
                st.close();
            }
        } catch (SQLException e) {
        }
    }

    public static void close(Connection connection) {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
        }
    }


    public static Connection  getConnection(String url,String driverClass, Properties props){
        Driver driver = ClassUtil.newInstance(driverClass);
        Connection conn;
        try {
            conn = driver.connect(url, props);
        } catch (SQLException e){
            throw new ServiceException(CommonCode.DB_ERROR,e);
        }

        if (conn == null) {
            throw new ServiceException("连结出错");
        }
        return conn;

    }

    public static boolean dbTypeIf(String dbUrl, String dbType) {
        return dbUrl.toLowerCase().contains(dbType);
    }

    public static boolean dbTypeIsMySQL(String dbUrl) {
        return dbTypeIf(dbUrl, "mysql") || dbTypeIf(dbUrl, "mariadb") || dbTypeIf(dbUrl, "sqlite") || dbTypeIf(dbUrl, "clickhouse") || dbTypeIf(dbUrl, "polardb");
    }

    public static boolean dbTypeIsOracle(String dbType) {
        return dbTypeIf(dbType, "oracle9i") || dbTypeIf(dbType, "oracle") || dbTypeIf(dbType, "dm") || dbTypeIf(dbType, "edb");
    }

    public static boolean dbTypeIsSQLServer(String dbType) {
        return dbTypeIf(dbType, "sqlserver") || dbTypeIf(dbType, "sqlserver2012") || dbTypeIf(dbType, "derby");
    }

    public static boolean dbTypeIsPostgre(String dbType) {
        return dbTypeIf(dbType, "postgresql") || dbTypeIf(dbType, "kingbase") || dbTypeIf(dbType, "zenith");
    }


}





